package com.gexin.model.order;

import com.alibaba.fastjson.JSONArray;
import com.alipay.AlipaySDK;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gexin.common.AppConst;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.SQLUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.order.base.BaseOrder;
import com.gexin.model.shop.ShopInfo;
import com.gexin.model.system.AdminLog;
import com.gexin.model.system.AdminLog.Log_Type;
import com.gexin.model.weixin.UserAddress;
import com.gexin.plugin.sqlinxml.SqlKit;
import com.gexin.weixin.uitls.WxConfig;
import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.PaymentApi;
import java.math.BigDecimal;
import java.util.*;

public class Order
		extends BaseOrder<Order>
{
	public static final Order dao = new Order();
	public static final int PayState_Wait = 1;
	public static final int PayState_PayOk = 2;
	public static final int PayState_Refund = 3;
	public static final int Js_Flag_WaitReceipt = 1;
	public static final int Js_Flag_Wait = 2;
	public static final int Js_Flag_OK = 3;
	public static final int plateform_Weixin = 1;
	public static final int plateform_App = 2;
	public static final int plateform_Web = 3;
	public static final String Sale_Type_GroupPay = "group_buy";
	public static final String Sale_Type_Pay = "buy";
	public static final int State_Wait_Pay = 0;
	public static final int State_Wait_Send_Express = 1;
	public static final int State_Send_Express = 2;
	public static final int State_Finish = 3;
	public static final int State_Close = 5;
	public static final int State_Refund_Ing = 0;
	static final Log log = Log.getLog(Order.class);
	private final String paginate_Filed = "select orders.sku_text,orders.id,orders.sum_price ,orders.product_id, orders.state,orders.payid,orders.createtime, orders.price, orders.postage ,product.center_image,product.product_name";



	public List<Order> getOrderList(Integer id){
		List<Order> orderList=Order.dao.find("select order_product_name,id,total_amount from t_order where user_id="+id);
		return orderList;
	}


	@Before({Tx.class})
	public AjaxCmd refund(String orderid, int type)
			throws RuntimeException
	{
		Order order = (Order)findById(orderid);
		if (order == null) {
			return new AjaxCmd(false, "��������������");
		}
		if (order.getPayState().intValue() != 2) {
			return new AjaxCmd(false, "������������������");
		}
		String refund_id = IdGenerateUtils.getOrderId();
		String out_refund_id = null;
		boolean execute_state = false;
		if ((order.getPayType().intValue() == 1) || (order.getPayType().intValue() == 4))
		{
			Map<String, String> para_map = new HashMap();
			para_map.put("transaction_id", order.getTransactionId());
			para_map.put("out_refund_no", refund_id);
			para_map.put("total_fee", order.getTotalFee() + "");
			para_map.put("refund_fee", order.getTotalFee() + "");
			Map<String, String> result_map = null;
			if (order.getPayType().intValue() == 1)
			{
				para_map.put("appid", WxConfig.AppID);
				para_map.put("mch_id", WxConfig.WXMchid);
				para_map.put("op_user_id", WxConfig.WXMchid);
				result_map = PaymentApi.refund(para_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
			}
			else
			{
				para_map.put("appid", WxConfig.APP_AppID);
				para_map.put("mch_id", WxConfig.APP_WXMchid);
				para_map.put("op_user_id", WxConfig.APP_WXMchid);
				result_map = PaymentApi.refund(para_map, WxConfig.APP_WXKEY, WxConfig.APP_KEYSTORE_FILE);
			}
			if (result_map == null) {
				return new AjaxCmd(false, "����������������������");
			}
			execute_state = ((String)result_map.get("result_code")).equals("SUCCESS");
			if (!execute_state) {
				return new AjaxCmd(false, (String)result_map.get("return_msg"));
			}
			out_refund_id = (String)result_map.get("refund_id");
		}
		else if (order.getPayType().intValue() == 5)
		{
			AlipayTradeRefundResponse response = AlipaySDK.refund(order.getId(), order.getTotalAmount().toString());
			if (response == null) {
				return new AjaxCmd(false, "����������������������");
			}
			if (!response.isSuccess()) {
				return new AjaxCmd(false, response.getMsg());
			}
			execute_state = true;
			out_refund_id = order.getId();
		}
		if (execute_state)
		{
			order.setPayState(Integer.valueOf(3));
			order.setState(OrderState.State_Refund);
			order.setModifiedTime(new Date());
			order.update();

			OrderRefund refund = new OrderRefund();
			refund.setRefundId(refund_id);
			refund.setOrderId(order.getId());
			int total = (int)(order.getTotalAmount().doubleValue() * 100.0D);
			refund.setRefundFee(Integer.valueOf(total));
			refund.setRefundRecvAccout(AppConst.Pay_Type.get(order.getPayType()).toString());
			refund.setState(Integer.valueOf(1));
			refund.setOutRefundNo(out_refund_id);
			refund.save();
			if (type == 2) {}
			return new AjaxCmd(true, "����������");
		}
		return new AjaxCmd(false, "����������");
	}

	public AjaxCmd refund(BigDecimal price, String orderid)
			throws RuntimeException
	{
		Order order = (Order)findById(orderid);
		if (order == null) {
			return new AjaxCmd(false, "��������������");
		}
		if (order.getPayState().intValue() != 2) {
			return new AjaxCmd(false, "������������������");
		}
		int total = (int)(price.doubleValue() * 100.0D);
		if (total > order.getTotalFee().intValue()) {
			return new AjaxCmd(false, "������������������������������");
		}
		String refund_id = IdGenerateUtils.getOrderId();
		String out_refund_id = null;
		boolean execute_state = false;
		if ((order.getPayType().intValue() == 1) || (order.getPayType().intValue() == 4))
		{
			Map<String, String> para_map = new HashMap();
			para_map.put("transaction_id", order.getTransactionId());
			para_map.put("out_refund_no", refund_id);
			para_map.put("total_fee", order.getTotalFee() + "");
			para_map.put("refund_fee", total + "");
			Map<String, String> result_map = null;
			if (order.getPayType().intValue() == 1)
			{
				para_map.put("appid", WxConfig.AppID);
				para_map.put("mch_id", WxConfig.WXMchid);
				para_map.put("op_user_id", WxConfig.WXMchid);
				result_map = PaymentApi.refund(para_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
			}
			else
			{
				para_map.put("appid", WxConfig.APP_AppID);
				para_map.put("mch_id", WxConfig.APP_WXMchid);
				para_map.put("op_user_id", WxConfig.APP_WXMchid);
				result_map = PaymentApi.refund(para_map, WxConfig.APP_WXKEY, WxConfig.APP_KEYSTORE_FILE);
			}
			if (result_map == null) {
				return new AjaxCmd(false, "����������������������");
			}
			execute_state = ((String)result_map.get("result_code")).equals("SUCCESS");
			if (!execute_state) {
				return new AjaxCmd(false, (String)result_map.get("return_msg"));
			}
			out_refund_id = (String)result_map.get("refund_id");
		}
		else if (order.getPayType().intValue() == 5)
		{
			AlipayTradeRefundResponse response = AlipaySDK.refund(order.getId(), price.doubleValue() + "");
			if (response == null) {
				return new AjaxCmd(false, "����������������������");
			}
			if (!response.isSuccess()) {
				return new AjaxCmd(false, response.getMsg());
			}
			execute_state = true;
			out_refund_id = order.getId();
		}
		if (execute_state)
		{
			order.setModifiedTime(new Date());
			order.setRefundAmount(order.getRefundAmount().add(price));
			order.setRefundRemark(StringUtil.show(order.getRefundRemark()) + "����:" + price.doubleValue() + "��;");
			if (order.getRefundAmount().doubleValue() == order.getTotalAmount().doubleValue())
			{
				order.setPayState(Integer.valueOf(3));
				order.setState(OrderState.State_Refund);
			}
			order.update();

			OrderRefund refund = new OrderRefund();
			refund.setRefundId(refund_id);
			refund.setOrderId(order.getId());
			refund.setRefundFee(Integer.valueOf(total));
			refund.setRefundRecvAccout(AppConst.Pay_Type.get(order.getPayType()).toString());
			refund.setState(Integer.valueOf(1));
			refund.setOutRefundNo(out_refund_id);
			refund.save();

			return new AjaxCmd(true, "����������");
		}
		return new AjaxCmd(false, "����������");
	}

	@Before({Tx.class})
	public void receipt_ConfirmMoney(String order_id)
	{
		Order order = (Order)dao.findByIdLoadColumns(order_id, "id,state,shop_id,js_amount,js_flag");
		if (order.getJsFlag().intValue() == 2)
		{
			order.setModifiedTime(new Date());
			order.setJsFlag(Integer.valueOf(3));
			order.update();
		}
		else
		{
			log.info("������������������");
			return;
		}
	}

	@Before({Tx.class})
	public void deliver_goods(String order_id)
	{
		Order order = (Order)dao.findByIdLoadColumns(order_id, "id,state,shop_id,total_amount,js_flag");
		if (order.getState() == OrderState.State_Express_OK)
		{
			order.setJsFlag(Integer.valueOf(3));
			order.setModifiedTime(new Date());
			order.update();
		}
		else
		{
			log.info("orderId:" + order.getId() + "������������������");
			return;
		}
	}

	@Before({Tx.class})
	public void receipt_goods(String order_id)
	{
		Order order = (Order)dao.findByIdLoadColumns(order_id, "id,state,shop_id,js_amount,js_flag");
		if (order.getState() == OrderState.State_Express_OK)
		{
			order.setState(OrderState.State_Complete);
			order.setJsFlag(Integer.valueOf(3));
			order.setReceiptTime(new Date());
			order.setModifiedTime(new Date());
			order.update();
		}
		else
		{
			log.info("orderId:" + order.getId() + "������������������");
			return;
		}
	}

	public AjaxCmd send_express(String orderid, String express_no, String express_name)
	{
		Order order = (Order)dao.findById(orderid);
		if (order == null)
		{
			AdminLog.dao.addLog(AdminLog.Log_Type.LOG_ERROR, Integer.valueOf(1), "��������������ID��������" + orderid);
			return new AjaxCmd(false, "��������������ID������");
		}
		if (order.getState() != OrderState.State_Pay_OK)
		{
			AdminLog.dao.addLog(AdminLog.Log_Type.LOG_ERROR, Integer.valueOf(1), String.format("��������������ID:%s,��������%s,��������", new Object[] { orderid, AppConst.Procuct_State.get(order.getState().toString()) }));
			return new AjaxCmd(false, "��������������������������");
		}
		if ((StringUtil.isNotBlank(express_name)) && (StringUtil.isNotBlank(express_no)))
		{
			order.setExpressName(express_name);
			order.setExpressNo(express_no);
			order.setState(OrderState.State_Express_OK);
			order.setModifiedTime(new Date());
			order.setExpressTime(new Date());
			if (order.update())
			{
				OrderExpress express = new OrderExpress();
				express.setOrderId(orderid);
				express.setExpressCom(order.getExpressName());
				express.setExpressNo(order.getExpressNo());
				express.save();
				return new AjaxCmd(true);
			}
			return new AjaxCmd(false, "����������������������������");
		}
		log.error("����������������");
		return new AjaxCmd(false, "����������������������������");
	}

	public static String getOrderSql(Order obj)
	{
		SQLUtils sql = new SQLUtils(" from t_product_order as orders ,t_product as product where  orders.product_id=product.id ");
		if (obj != null)
		{
			if (obj.getState() != null) {
				sql.whereEquals("state", obj.getState());
			}
			if (StringUtil.isNotBlank(obj.getId())) {
				sql.whereEquals("orders.id", obj.getId());
			}
			if (StringUtil.isNotBlank(obj.getPayId())) {
				sql.whereEquals("orders.payid", obj.getPayId());
			}
			if ((StringUtil.isNotBlank(obj.getStr("req1"))) && (StringUtil.isNotBlank(obj.getStr("req2")))) {
				sql.append(String.format(" and orders.createtime BETWEEN '%s' and '%s' ", new Object[] { obj.getStr("req1"), obj.getStr("req2") }));
			}
			if (StringUtil.isNotBlank(obj.getStr("userphone"))) {
				sql.whereEquals("orders.express_phone", obj.getStr("userphone"));
			}
			if (StringUtil.isNotBlank(obj.getStr("agent_id"))) {
				sql.whereEquals("orders.agent_id", obj.getStr("userphone"));
			}
		}
		if ((obj.getState() != null) && (obj.getState().intValue() != 0)) {
			sql.append(" order by orders.paytime " + obj.getStr("sort"));
		} else {
			sql.append(" order by orders.createtime " + obj.getStr("sort"));
		}
		return sql.toString();
	}

	public Page<Order> paginate(Order obj, int pageNumber, int pageSize)
	{
		return dao.paginate(pageNumber, pageSize, "select orders.sku_text,orders.id,orders.sum_price ,orders.product_id, orders.state,orders.payid,orders.createtime, orders.price, orders.postage ,product.center_image,product.product_name", getOrderSql(obj));
	}

	public List<Order> out_excel(Order obj)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("order.excel_list"));
		if (obj != null)
		{
			if (obj.getState() != null) {
				sql.whereEquals("orders.state", obj.getState());
			}
			if (StringUtil.isNotBlank(obj.getId())) {
				sql.whereEquals("orders.id", obj.getId());
			}
			if (StringUtil.isNotBlank(obj.getPayId())) {
				sql.whereEquals("orders.payid", obj.getPayId());
			}
			if ((StringUtil.isNotBlank(obj.getStr("req1"))) && (StringUtil.isNotBlank(obj.getStr("req2")))) {
				sql.append(String.format(" and orders.createtime BETWEEN '%s' and '%s' ", new Object[] { obj.getStr("req1"), obj.getStr("req2") }));
			}
			if (StringUtil.isNotBlank(obj.getStr("userphone"))) {
				sql.whereEquals("orders.express_phone", obj.getStr("userphone"));
			}
		}
		sql.append(" order by orders.paytime asc");
		return dao.find(sql.toString());
	}

	public Order getOrderById(String order_id)
	{
		return (Order)dao.findFirst(SqlKit.sql("order.detail"), new Object[] { order_id });
	}


	public List<Order> getOrderListByUserId(Integer state, String user_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where state !=5 ");
		if (StringUtil.isNotBlank(user_id)) {
			sql.whereEquals("user_id ", user_id);
		}
		if (state != null) {
			sql.whereEquals("state ", state);
		}
		sql.append(" order by createtime desc");
		return dao.find(sql.toString());
	}

	public List<Order> getOrderListByUserIdAndStatus(Integer state, String user_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where 1=1");
		if (StringUtil.isNotBlank(user_id)) {
			sql.whereEquals("user_id ", user_id);
		}
		if (state != null) {
			sql.whereEquals("state ", state);
		}
		sql.append(" order by createtime desc");
		return dao.find(sql.toString());
	}

	public List<Order> getOrderByUserId(Integer state, String user_id)
	{
		SQLUtils sql = new SQLUtils("select orders.sku_text,orders.id,orders.sum_price ," +
				"orders.product_id, orders.state,orders.payid,orders.createtime, orders.price, " +
				"orders.postage ,product.center_image,product.product_name from t_product_order " +
				"as orders ,t_product as product  where orders.state !=5 " +
				"and orders.product_id=product.id ");
		if (StringUtil.isNotBlank(user_id	)) {
			sql.whereEquals(" orders.user_id ", user_id);
		}
		if (state != null) {
			sql.whereEquals(" orders.state ", state);
		}
		sql.append(" order by orders.createtime desc");
		return dao.find(sql.toString());
	}

	@Before({Tx.class})
	public AjaxCmd closeOrder(String order_id)
	{
		Order order = (Order)dao.findById(order_id);
		if (order == null) {
			return new AjaxCmd(false, "������������");
		}
		if (order.getState().intValue() != 0) {
			return new AjaxCmd(false, "��������������������");
		}
		order.setState(OrderState.State_Closed);
		order.setModifiedTime(new Date());
		boolean res = order.update();
		if ((res) &&
				(StringUtil.isNotBlank(order.getCouponId()))) {
			Db.update("update t_user_coupon set use_state=0 where id = ?", new Object[] { order.getCouponId() });
		}
		return new AjaxCmd(res);
	}

	public Order getOrderAddress(String orderid)
	{
		return (Order)dao.findFirst(SqlKit.sql("order.getOrderAddress"), new Object[] { orderid });
	}

	public List<Order> cache_getOrderByUserId(String user_id)
	{
		List<Order> list = (List)CacheUtils.get("order:user:" + user_id);
		if ((list == null) || (list.size() == 0))
		{
			list = find(SqlKit.sql("product.getOderByUserId"), new Object[] { user_id });
			CacheUtils.set("order:" + user_id, list, 180);
		}
		return list;
	}

	public int setProductSumPrice(String order_id, double price)
	{
		return Db.update("update t_product_order  set sum_price=? where id=?", new Object[] { Double.valueOf(price), order_id });
	}

	public Page<Order> paginate_push_list(String shop_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.index"));
		sql.whereEquals("state", OrderState.State_Pay_OK);

		sql.append(" and  o.interface_state in (1,97) ");
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if (order.getInt("product_id") != null) {
				sql.whereEquals(" i.product_id", order.getInt("product_id"));
			}
			if ((start_time != null) && (end_time != null)) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
		}
		sql.append(" and o.shop_id = '" + shop_id + "'");
		sql.append(" order by o.createtime asc");

		return dao.paginate(pageNumber, pageSize, "select o.* ,i.item_id ", sql.toString());
	}

	public Page<Order> paginate(String shop_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(" from t_order o ");
 		sql.append(" left join t_order_item i on i.order_id=o.id ");
		sql.append(" left join t_order_state s on o.state=s.state_id where true ");
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				if (order.getState().intValue() == 6) {
					sql.whereEquals("i.refund_state", Integer.valueOf(2));
				} else {
					sql.whereEquals("state", order.getState());
				}
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereLike("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if (order.getInt("product_id") != null) {
				sql.whereEquals(" i.product_id", order.getInt("product_id"));
			}
			if (order.getOrderPlatform() != null) {
				sql.whereEquals("order_platform", order.getOrderPlatform());
			}
			if ((StringUtil.isNotBlank(start_time)) || (StringUtil.isNotBlank(end_time))) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
		}
		sql.append(" and o.shop_id = '" + shop_id + "'");
		sql.append("  group by o.id order by o.createtime desc ");
		return dao.paginate(pageNumber, pageSize, " select o.* ,i.item_id,s.state_name ", sql.toString());
	}

	public List<Order> shangjia_excel(String shop_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(" from t_order o LEFT JOIN  t_order_item i on i.order_id=o.id where 1=1 ");
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				sql.whereEquals("state", order.getState());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if (order.getInt("product_id") != null) {
				sql.whereEquals(" i.product_id", order.getInt("product_id"));
			}
			if ((StringUtil.isNotBlank(start_time)) || (StringUtil.isNotBlank(end_time)))
			{
				if (StringUtil.isBlank(start_time)) {
					start_time = null;
				}
				if (StringUtil.isBlank(end_time)) {
					end_time = null;
				}
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
		}
		if (StringUtil.isNotBlank(shop_id)) {
			sql.whereEquals("o.shop_id", shop_id);
		}
		sql.append(" group by o.id  order by o.createtime desc");
		return dao.find(" select o.* ,group_concat(i.item_id separator ',') item_id " + sql.toString());
	}

	public List<Order> shangjia_refund_excel(String shop_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.index"));
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				sql.whereEquals("state", order.getState());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if ((StringUtil.isNotBlank(start_time)) || (StringUtil.isNotBlank(end_time))) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
		}
		sql.append(" and o.shop_id = '" + shop_id + "'");

		sql.append(" and i.refund_state!=1 ");
		sql.append(" group by o.id  order by o.createtime desc ");
		return dao.find("select o.* ,i.item_id " + sql.toString());
	}

	public Order getOrderDetailById(String order_id)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.getOrderDetailByOrderId"));
		return (Order)dao.findFirst(sql.toString(), new Object[] { order_id });
	}

	public Page<Order> supplier_paginate(int supplier_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.index"));
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				sql.whereEquals("state", order.getState());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if ((start_time != null) && (end_time != null)) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
			if (order.getShopId() != null) {
				sql.append(" and o.shop_id = '" + order.getShopId() + "'");
			}
		}
		sql.append(" and o.supplier_id= " + supplier_id);
		sql.append(" order by o.createtime desc");
		return dao.paginate(pageNumber, pageSize, "select o.* ", sql.toString());
	}

	public List<Order> supplier_excel(int supplier_id, Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.index"));
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				sql.whereEquals("state", order.getState());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if ((start_time != null) && (end_time != null)) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
			if (order.getShopId() != null) {
				sql.append(" and o.shop_id = '" + order.getShopId() + "'");
			}
		}
		sql.append(" and o.supplier_id=" + supplier_id);
		sql.append(" order by o.createtime desc");
		return dao.find("select o.* ,i.item_id " + sql.toString());
	}

	public List<Order> getLastFourOrderBySupplier(int supplier_id)
	{
		String sql = " select o.*  from t_order o where  o.supplier_id=? and o.state >0 order by createtime desc limit  0,5  ";
		return dao.find(sql, new Object[] { Integer.valueOf(supplier_id) });
	}

	public Page<Order> paginate(Order order, String start_time, String end_time, int pageNumber, int pageSize)
	{
		SQLUtils sql = new SQLUtils(SqlKit.sql("shoporder.index"));
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				sql.whereEquals("state", order.getState());
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereEquals("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if (order.getShopId() != null) {
				sql.append(" and o.shop_id = '" + order.getShopId() + "'");
			}
			if (order.getInt("product_id") != null) {
				sql.whereEquals(" i.product_id", order.getInt("product_id"));
			}
		}
		if ((start_time != null) && (end_time != null)) {
			sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
		}
		sql.append(" order by o.createtime desc");
		return dao.paginate(pageNumber, pageSize, "select o.* ,i.item_id ", sql.toString());
	}

	public List<Order> getOrderByShopId(int page, String shop_id, String state, String supply_type)
	{
		if ((supply_type.equals("1")) || (supply_type.equals("2")))
		{
			SQLUtils sql = new SQLUtils(" select *  from t_order where shop_id=? and state=? and supply_type=? ");
			sql.append(" order by createtime desc LIMIT ?,? ");
			return dao.find(sql.toString(), new Object[] { shop_id, state, supply_type, Integer.valueOf(page * 10), Integer.valueOf(10) });
		}
		if (state.equals("2"))
		{
			SQLUtils sql = new SQLUtils(" select *  from t_order where shop_id=? and state=? ");
			sql.append(" order by express_time desc LIMIT ?,? ");
			return dao.find(sql.toString(), new Object[] { shop_id, state, Integer.valueOf(page * 10), Integer.valueOf(10) });
		}
		if (state.equals("1"))
		{
			SQLUtils sql = new SQLUtils(" select *  from t_order where shop_id=? and state=? ");
			sql.append(" order by pay_time desc LIMIT ?,? ");
			return dao.find(sql.toString(), new Object[] { shop_id, state, Integer.valueOf(page * 10), Integer.valueOf(10) });
		}
		if (state.equals("3"))
		{
			SQLUtils sql = new SQLUtils(" select *  from t_order where shop_id=? and state=? ");
			sql.append(" order by receipt_time desc LIMIT ?,? ");
			return dao.find(sql.toString(), new Object[] { shop_id, state, Integer.valueOf(page * 10), Integer.valueOf(10) });
		}
		SQLUtils sql = new SQLUtils(" select *  from t_order where shop_id=? and state=? ");
		sql.append(" order by createtime desc LIMIT ?,? ");
		return dao.find(sql.toString(), new Object[] { shop_id, state, Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public Order app_getOrderById(String id)
	{
		String sql = " select *  from t_order where id=? ";

		return (Order)dao.findFirst(sql, new Object[] { id });
	}

	public List<Order> getOrderByState(int page, int state)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where state=? ");
		sql.append(" order by createtime desc LIMIT ?,? ");
		return dao.find(sql.toString(), new Object[] { Integer.valueOf(state), Integer.valueOf(page * 10), Integer.valueOf(10) });
	}

	public Order getOrderByOrderId(String order_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where id=? ");
		return (Order)dao.findFirst(sql.toString(), new Object[] { order_id });
	}

	public List<Order> getOrderListByOrderId(String order_id, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where 1=1 ");
		sql.whereLike("id", order_id);
		sql.whereEquals("shop_id", shop_id);
		sql.append(" order by createtime desc ");
		return dao.find(sql.toString());
	}

	public List<Order> getOrderByName(String receive_name, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where 1=1 ");
		sql.whereLike("express_receive_name", receive_name);
		sql.whereEquals("shop_id", shop_id);
		sql.append(" order by createtime desc ");
		return dao.find(sql.toString());
	}

	public List<Order> getOrderByPhone(String phone, String shop_id)
	{
		SQLUtils sql = new SQLUtils("select * from t_order where 1=1 ");
		sql.whereLike("express_phone", phone);
		sql.whereEquals("shop_id", shop_id);
		sql.append(" order by createtime desc ");
		return dao.find(sql.toString());
	}

	public Page<Order> refundPaginate(String shop_id, Order order, String start_time, String end_time, int pageNumber, int pageSize, int refund)
	{
		SQLUtils sql = new SQLUtils(" from t_order o where 1=1 ");
		if (refund == 2) {
			sql.append(" and id in (select distinct order_id from t_order_item where refund_state=2 ) ");
		} else if (refund == 5) {
			sql.append(" and id in (select distinct order_id from t_order_item where refund_state=5) ");
		} else if (refund == 3) {
			sql.append(" and id in (select distinct order_id from t_order_item where refund_state=3) ");
		} else if (refund == 4) {
			sql.append(" and id in (select distinct order_id from t_order_item where refund_state=4 ) ");
		} else {
			sql.append(" and id in (select distinct order_id from t_order_item where refund_state!=1 ) ");
		}
		if (order != null)
		{
			if (order.getId() != null) {
				sql.whereEquals("id", order.getId());
			}
			if (order.getState() != null) {
				if (order.getState().intValue() == 6) {
					sql.append(" and id in (select distinct order_id from t_order_item where refund_state=2 ) ");
				} else {
					sql.whereEquals("state", order.getState());
				}
			}
			if (order.getExpressReceiveName() != null) {
				sql.whereLike("express_receive_name", order.getExpressReceiveName());
			}
			if (StringUtil.isNotBlank(order.getExpressPhone())) {
				sql.whereLike("express_phone", order.getExpressPhone());
			}
			if ((StringUtil.isNotBlank(start_time)) || (StringUtil.isNotBlank(end_time))) {
				sql.append(" and o.createtime >= '" + start_time + "' and  o.createtime <= '" + end_time + "'");
			}
		}
		sql.append(" and o.shop_id = '" + shop_id + "'");
		sql.append(" order by o.createtime desc");
		return dao.paginate(pageNumber, pageSize, "select o.* ", sql.toString());
	}

	public Order getLastMonth(String shop_id)
	{
		String sql = "select sum(item_amount) as lastMonth from t_order where shop_id=? and pay_state=2 and DATE_FORMAT(pay_time,'%Y-%m')=DATE_FORMAT(DATE_SUB(CURDATE(),INTERVAL 1 MONTH),'%Y-%m')";
		return (Order)dao.findFirst(sql, new Object[] { shop_id });
	}

	public Order getThisMonth(String shop_id)
	{
		String sql = "select sum(item_amount) as thisMonth from t_order where shop_id=? and pay_state=2 and DATE_FORMAT(pay_time,'%Y-%m')=DATE_FORMAT(CURDATE(),'%Y-%m')";
		return (Order)dao.findFirst(sql, new Object[] { shop_id });
	}

	public Long findAgentSize(Integer agentId)
	{
		SQLUtils sql = new SQLUtils();
		sql.append(" select count(*) from t_order o ");
		sql.append(" LEFT JOIN t_agent ta ON ta.id=o.agent_id ");
		sql.append(" where ta.id=? or ta.parent_id=? ");

		return Db.queryLong(sql.toString(), new Object[] { agentId, agentId });
	}

	public Page<Order> findAgentOrders(Integer agentId, Integer page, Integer pageSize, String startTime, String endTime, String state, String type, String cityId)
	{
		SQLUtils sql = new SQLUtils();

		sql.append(" from t_order o ");
		sql.append(" LEFT JOIN t_agent agent on o.agent_id= agent.id ");
		sql.append(" where o.agent_id=? ");
		if (StringUtil.isNotBlank(state)) {
			sql.whereEquals("o.state", state);
		}
		if (StringUtil.isNotBlank(type)) {
			sql.whereEquals("o.type", type);
		}
		if (StringUtil.isNotBlank(cityId)) {
			sql.whereEquals("agentCity.id", cityId);
		}
		if ((StringUtil.isNotBlank(startTime)) && (StringUtil.isNotBlank(endTime))) {
			sql.between("o.createtime", startTime, endTime);
		}
		sql.append(" order by o.createtime  desc ");

    		return paginate(page.intValue(), pageSize.intValue(), "select o.* ", sql.toString(), new Object[] { agentId });
	}

	public Page<Order> findErJiAgentOrders(Integer agentId, Integer page, Integer pageSize, String startTime, String endTime, String state, String type)
	{
		SQLUtils sql = new SQLUtils();
		sql.append(" from t_order o ");
		sql.append(" LEFT JOIN t_agent agent on o.agent_id= agent.id ");
		if (StringUtil.isBlank(type)) {
			sql.append("where agent.id=" + agentId + " or agent.parent_id=" + agentId);
		} else if ("1".equals(type)) {
			sql.append("where  agent.parent_id=" + agentId);
		} else if ("0".equals(type)) {
			sql.append("where agent.id=" + agentId);
		} else {
			sql.append("where agent.id=" + agentId + " or agent.parent_id=" + agentId);
		}
		if (StringUtil.isNotBlank(state)) {
			sql.whereEquals("o.state", state);
		}
		if ((StringUtil.isNotBlank(startTime)) && (StringUtil.isNotBlank(endTime))) {
			sql.between("o.createtime", startTime, endTime);
		}
		sql.append(" order by o.createtime  desc ");

		return paginate(page.intValue(), pageSize.intValue(), "select o.* ", sql.toString());
	}

	public Page<Order> findUserIdList(int page, int pageSize, Order order)
	{
		SQLUtils sql = new SQLUtils(" from t_order o ");
		sql.append(" left join t_order_item i on i.order_id=o.id ");
		sql.append(" left join t_order_state s on o.state=s.state_id where true ");
		if (order != null) {
			if (order.getUserId() != null) {
				sql.whereLike("o.user_id", order.getUserId().toString());
			}
		}
		sql.append("  group by o.id order by o.createtime desc");
		return dao.paginate(page, pageSize, " select o.* ,i.item_id,s.state_name ", sql.toString());
	}

	public Page<Order> findAreaAgentOrders(Integer agentId, Integer page, Integer pageSize, String startTime, String endTime, String state, String type)
	{
		SQLUtils sql = new SQLUtils();
		sql.append(" from t_order o ");
		sql.append(" LEFT JOIN t_user_address address on address.id=o.address_id ");
		sql.append(" LEFT JOIN t_addr_cities city ON city.cityid=address.city_id ");
		sql.append(" LEFT JOIN t_agent agent on city.agent_id= agent.id ");
		sql.append(" LEFT JOIN  t_agent agorder on agorder.id= o.agent_id ");
		if (StringUtil.isBlank(type)) {
			sql.append("where agent.id=" + agentId + " or agent.parent_id=" + agentId + " or agorder.id=" + agentId + " or agorder.parent_id=" + agentId + " ");
		} else if ("1".equals(type)) {
			sql.append("where  agent.parent_id=" + agentId + " or agorder.id=" + agentId + " or agorder.parent_id=" + agentId + " ");
		} else if ("0".equals(type)) {
			sql.append("where agent.id=" + agentId);
		} else {
			sql.append("where agent.id=" + agentId + " or agent.parent_id=" + agentId);
		}
		if (StringUtil.isNotBlank(state)) {
			sql.whereEquals("o.state", state);
		}
		if ((StringUtil.isNotBlank(startTime)) && (StringUtil.isNotBlank(endTime))) {
			sql.between("o.createtime", startTime, endTime);
		}
		sql.append(" order by o.createtime  desc ");

		return paginate(page.intValue(), pageSize.intValue(), "select o.* ", sql.toString());
	}

	public Long findAreaAgentSize(Integer agentId)
	{
		SQLUtils sql = new SQLUtils();
		sql.append(" select count(*) from t_order o ");
		sql.append(" LEFT JOIN t_user_address address on address.id=o.address_id ");
		sql.append(" LEFT JOIN t_addr_cities city ON city.cityid=address.city_id ");
		sql.append(" LEFT JOIN t_addr_areas area on area.areaid=address.county_id  ");
		sql.append(" LEFT JOIN t_agent agorder on agorder.id= o.agent_id  ");
		sql.append(" where (city.agent_id=? or area.agent_id=? or agorder.id=? or agorder.parent_id=?)");
		return Db.queryLong(sql.toString(), new Object[] { agentId, agentId, agentId, agentId });
	}

	public Order findByAddress(String addressId)
	{
		SQLUtils sql = new SQLUtils();
		sql.append(" select * from t_order o  where o.address_id=?");

		return (Order)findFirst(sql.toString(), new Object[] { addressId });
	}


/*-----------------------------------------------------------------------------------------------*/

	public void setUserIdAndPlatformAndRegisterOrderAndAddressAndPayTypeAndPhoneAndDanjiaAndMoneyAndBuyCount(
			String userId,int isXapp,int registerOrder,UserAddress address,String phone,
			BigDecimal totalAmount,String shopId,int type,int status,int payType,int payState){
//		type:类型 state状态表 payType支付方式 paystate支付状态
		this.setId(IdGenerateUtils.getOrderId());// 订单ID
		this.setPayId(this.getId());
		this.setUserId(Integer.parseInt(userId));//
		this.setOrderPlatform(isXapp);
		this.setRegisterOrder(registerOrder);
		//初始化地址信息
		this.setExpressAddress(address.getAddress());// 收货详细信息
		this.setExpressReceiveName(address.getConsignee());// 收货人姓名
		this.setExpressZipCode("000000");// 邮编信息
		this.setExpressPhone(address.getPhone());// 手机号码
		this.setAddressId(address.getId());
		this.setTailNoticePhone(phone);
		this.setTotalAmount(totalAmount);

		this.setShopId(shopId);
		this.setPayType(payType);//7代表兑换券兑换
		this.setPayState(payState);
		this.setType(type);
		this.setState(status);
	}


}
